package LC;

import java.util.ArrayList;

/**
 * https://leetcode.com/problems/restore-ip-addresses/description/
 * Given a string containing only digits, restore it by returning all possible valid IP address combinations.
 * For example:
 * Given "25525511135",
 * return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
 */
public class LC_093_RestoreIPAddresses_DFS_BackTracking {
    public static void main(String[] args) {
        ArrayList<String> list = Solution.restoreIpAddresses("25525511135");
        System.out.println(list);
    }

    static class Solution {
        static ArrayList<String> restoreIpAddresses(String s) {
            ArrayList<String> res = new ArrayList<>();
            String item = "";
            if (s.length() < 4 || s.length() > 12) return res;
            dfs(s, 0, item, res);
            return res;
        }

        private static void dfs(String s, int start, String item, ArrayList<String> res) {
            if (start == 3 && isValid(s)) {
                res.add(item + s);
                return;
            }
            for (int i = 0; i < 3 && i < s.length() - 1; i++) {
                String subStr = s.substring(0, i + 1);
                if (isValid(subStr))
                    dfs(s.substring(i + 1, s.length()), start + 1, item + subStr + '.', res);
            }
        }

        private static boolean isValid(String s) {
            if (s.charAt(0) == '0')
                return s.equals("0");
            int num = Integer.parseInt(s);
            return num <= 255 && num > 0;
        }
    }
}
